package http

import (
	"context"
	"core/id"
	"core/server/baseserver"
	"fmt"
	"github.com/dubbogo/gost/log/logger"
	"io"
	"iotall/iotcore/api/proxyup"
	"iotall/iotcore/entity"
	"iotall/iotproxy/pkg"
	"iotall/iotproxy/proxyconfig"
	dataserver2 "iotall/iotproxy/server/dataserver"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type HttpServer struct {
	Server   *http.Server
	CommPort *entity.CommPort
}

func (p *HttpServer) SetCommPort(m *entity.CommPort) {
	p.CommPort = m
}
func (p *HttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var Method = strings.ToUpper(r.Method)
	var Url = r.RequestURI
	var smsg = fmt.Sprintf("%v\r\n%v\r\n", Method, Url)

	data, err := io.ReadAll(r.Body)
	if err == nil {
		smsg += string(data)
	} else {
		data = make([]byte, 0)
	}

	var Sid = ""
	var ReqId = id.NewId()
	var in = &proxyup.UpReq{
		ReqId:       ReqId,
		Sid:         Sid,
		RemoteAddr:  r.RemoteAddr,
		CommPortId:  p.CommPort.Id,
		CommProxyId: proxyconfig.Config.Id,
		Data:        data,
		P1:          Url,
		P2:          Method,
		P3:          "",
		P4:          "",
	}
	var mrev = &entity.CommData{
		Id:         ReqId,
		Sid:        Sid,
		Method:     "上传",
		CrtDt:      time.Now(),
		Data:       smsg,
		Memo:       "",
		CommPortId: p.CommPort.Id,
	}
	resp, err := pkg.ProxyUpClientImpl.Up(context.Background(), in)
	if err != nil {
		logger.Errorf("onUp %v", err)
		mrev.Memo = "解析失败" + err.Error()
	} else {
		Sid = resp.Sid

		mrev.Memo = resp.Msg
		mrev.Sid = Sid

	}
	//保存上传日志
	dataserver2.CommDataServer.AddData(mrev)

	if err != nil {
		return
	}
	w.Header().Add("content-type", "application/json")
	w.WriteHeader(200)
	if len(resp.Data) > 0 {
		var msend = &entity.CommData{
			Id:         id.NewId(),
			Sid:        Sid,
			Method:     "下发",
			CrtDt:      time.Now(),
			Data:       string(resp.Data),
			Memo:       resp.DownMsg,
			CommPortId: p.CommPort.Id,
		}

		//保存下发日志
		dataserver2.CommDataServer.AddData(msend)
		w.Write(resp.Data)
	}

}
func (p *HttpServer) Start() {
	p.Server = &http.Server{
		Addr:    ":" + strconv.Itoa(int(p.CommPort.Port)),
		Handler: p,
	}
	go func() {
		logger.Infof("HttpServer 代理 %v 启动 端口:%d", p.CommPort.Name, p.CommPort.Port)
		baseserver.AddServer(p)
		var err = p.Server.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			logger.Fatalf("监听端口出现错误 %v", p.CommPort.Port)
			return
		}

	}()

}
func (p *HttpServer) Close() {
	var _ = p.Server.Shutdown(context.Background())

	logger.Infof("HttpServer 代理 %v 关闭 端口:%d", p.CommPort.Name, p.CommPort.Port)
}
